<?php
/**
 * 用户控制器
 */

namespace app\admin\controller;

use support\Request;
use support\Response;
use app\common\model\User;
use app\common\model\UserLevel;
use app\admin\traits\AdminCreateDataTrait;
use app\admin\traits\AdminDelTrait;
use app\admin\traits\AdminDisableTrait;
use app\admin\traits\AdminEnableTrait;
use app\admin\traits\AdminUpdateDataTrait;
use app\common\validate\UserValidate;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class UserController extends AdminBaseController
{

    use AdminCreateDataTrait;
    use AdminUpdateDataTrait;
    use AdminDelTrait;
    use AdminEnableTrait;
    use AdminDisableTrait;

    public function __construct()
    {
        $this->model    = new User();
        $this->validate = new UserValidate();
        parent::__construct();
    }

    /**
     * 列表
     * @param Request $request
     * @param User $model
     * @return Response
     * @throws DbException
     */
    public function index(Request $request, User $model): Response
    {
        $param = $request->all();
        $data  = $model->with('user_level')->scope('where', $param)
            ->paginate([
                'list_rows' => $this->admin['admin_list_rows'],
                'var_page'  => 'page',
                'query'     => $request->get(),
            ]);
        // 关键词，排序等赋值
        $this->assign($request->get());

        $this->assign([
            'data'            => $data,
            'page'            => $data->render(),
            'total'           => $data->total(),
            'user_level_list' => (new UserLevel)->select(),
            'status_list'     => User::STATUS_LIST,
        ]);
        return $this->fetch();
    }

    /**
     * 添加
     *
     * @param Request $request
     * @param User $model
     * @param UserValidate $validate
     * @return Response
     */
    public function add(Request $request, User $model, UserValidate $validate): Response
    {
        if ($request->method() === 'POST') {
            $this->createData($model, $validate);
        }

        try {
            $user_level_list = (new UserLevel)->select();
        } catch (DataNotFoundException | ModelNotFoundException | DbException $e) {
            $user_level_list = [];
        }

        $this->assign([
            'user_level_list' => $user_level_list,
        ]);

        return $this->fetch();
    }

    /**
     * 修改
     *
     * @param Request $request
     * @param User $model
     * @param UserValidate $validate
     * @return Response
     */
    public function edit(Request $request, User $model, UserValidate $validate): Response
    {
        $id   = $request->input('id');
        $data = $model->findOrEmpty($id);
        if ($request->method() === 'POST') {
            return $this->updateData($data, $validate);
        }

        try {
            $user_level_list = (new UserLevel)->select();
        } catch (DataNotFoundException | ModelNotFoundException | DbException $e) {
            $user_level_list = [];
        }

        $this->assign([
            'data'            => $data,
            'user_level_list' => $user_level_list,

        ]);

        return $this->fetch('add');
    }


    /**
     * 导入
     * @param Request $request
     * @return Response
     */
    public function import(Request $request): Response
    {
        $param           = $request->all();
        $field_name_list = ['用户等级', '账号', '密码', '手机号', '昵称', '头像', '是否启用',];
        if (isset($param['action']) && $param['action'] === 'download_example') {
            return $this->downloadExample($field_name_list);
        }

        $field_list = ['user_level_id', 'username', 'password', 'mobile', 'nickname', 'avatar', 'status',];
        $result     = $this->importData('file', 'user', $field_list);

        return true === $result ? admin_success('操作成功', [], URL_RELOAD) : admin_error($result);
    }

    /**
     * 导出
     * @param Request $request
     * @param User $model
     * @return Response
     */
    public function export(Request $request, User $model): Response
    {
        $param = $request->all();
        try {
            $data = $model->with('user_level')->scope('where', $param)->select();
        } catch (DataNotFoundException | ModelNotFoundException | DbException $e) {
            $data = [];
        }

        $header = ['ID', '用户等级', '账号', '手机号', '昵称', '头像', '是否启用', '创建时间',];
        $body   = [];
        foreach ($data as $item) {
            $record                  = [];
            $record['id']            = $item->id;
            $record['user_level_id'] = $item->user_level->name ?? '';
            $record['username']      = $item->username;
            $record['mobile']        = $item->mobile;
            $record['nickname']      = $item->nickname;
            $record['avatar']        = $item->avatar;
            $record['status']        = $item->status_text;
            $record['create_time']   = $item->create_time;

            $body[] = $record;
        }

        return $this->exportData($header, $body, '用户数据-' . date('YmdHis'));
    }

}
